import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getExamInfo, submitAnswer, submitExam } from '@/api/exam'

export const useExamStore = defineStore('exam', () => {
  const currentExam = ref(null)
  const answers = ref({})
  const timeRemaining = ref(0)
  const isSubmitted = ref(false)
  const currentQuestionIndex = ref(0)
  
  const questions = computed(() => currentExam.value?.questions || [])
  const totalQuestions = computed(() => questions.value.length)
  const answeredCount = computed(() => Object.keys(answers.value).length)
  const progress = computed(() => {
    if (totalQuestions.value === 0) return 0
    return Math.round((answeredCount.value / totalQuestions.value) * 100)
  })
  
  const currentQuestion = computed(() => {
    return questions.value[currentQuestionIndex.value] || null
  })
  
  // 加载考试信息
  const loadExam = async (examId) => {
    try {
      const response = await getExamInfo(examId)
      currentExam.value = response.data
      timeRemaining.value = response.data.duration * 60 // 转换为秒
      answers.value = {}
      isSubmitted.value = false
      currentQuestionIndex.value = 0
      return response.data
    } catch (error) {
      throw error
    }
  }
  
  // 保存答案
  const saveAnswer = async (questionId, answer) => {
    answers.value[questionId] = answer
    
    // 自动保存到服务器
    try {
      await submitAnswer({
        examId: currentExam.value.id,
        questionId,
        answer
      })
    } catch (error) {
      console.error('保存答案失败:', error)
    }
  }
  
  // 跳转到指定题目
  const goToQuestion = (index) => {
    if (index >= 0 && index < totalQuestions.value) {
      currentQuestionIndex.value = index
    }
  }
  
  // 下一题
  const nextQuestion = () => {
    if (currentQuestionIndex.value < totalQuestions.value - 1) {
      currentQuestionIndex.value++
    }
  }
  
  // 上一题
  const prevQuestion = () => {
    if (currentQuestionIndex.value > 0) {
      currentQuestionIndex.value--
    }
  }
  
  // 提交考试
  const submitExamAction = async () => {
    try {
      const response = await submitExam({
        examId: currentExam.value.id,
        answers: answers.value
      })
      isSubmitted.value = true
      return response.data
    } catch (error) {
      throw error
    }
  }
  
  // 开始倒计时
  const startTimer = () => {
    const timer = setInterval(() => {
      if (timeRemaining.value > 0) {
        timeRemaining.value--
      } else {
        clearInterval(timer)
        // 时间到，自动提交
        submitExamAction()
      }
    }, 1000)
    
    return timer
  }
  
  // 格式化时间显示
  const formatTime = computed(() => {
    const hours = Math.floor(timeRemaining.value / 3600)
    const minutes = Math.floor((timeRemaining.value % 3600) / 60)
    const seconds = timeRemaining.value % 60
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  })
  
  // 重置考试状态
  const resetExam = () => {
    currentExam.value = null
    answers.value = {}
    timeRemaining.value = 0
    isSubmitted.value = false
    currentQuestionIndex.value = 0
  }
  
  return {
    currentExam,
    answers,
    timeRemaining,
    isSubmitted,
    currentQuestionIndex,
    questions,
    totalQuestions,
    answeredCount,
    progress,
    currentQuestion,
    formatTime,
    loadExam,
    saveAnswer,
    goToQuestion,
    nextQuestion,
    prevQuestion,
    submitExamAction,
    startTimer,
    resetExam
  }
})